﻿/// <reference path="../../../ckeditor/config.js" />
/// <reference path="../../../ckeditor/config.js" />
/// <reference path="../../../ckeditor/config.js" />

var baseUrl = getBaseplatformPort();
$(function () {
    //样式 
    $("#news1").css("color", "#52b5f8");

    // 重置窗口大小
    function resizeWindow() {
        var DEBUG;
        //DEBUG = true;
        if (DEBUG) {
            [].forEach.call($($('*')), function (a) {
                a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
            });
        }
        // console.log('resize...');
        var minHeight = $('body').height() - $('#dataTreeDiv').offset().top - 20;
        $('#dataTreeDiv').css('max-height', minHeight);
        $('#main').css('height', $('body').height() - $('#main').offset().top - 20);
    }
    resizeWindow();
    // resize窗口
    window.onresize = function () {
        resizeWindow();
    };
    //显示列表
    function getTitleList(state,page, isSecond) {
        $('#userTable').html('');
        var date = $('#txt_date').val();
        var startDate = "";
        var endDate = "";
        if (date != "") {
            var strs = new Array();
            strs = date.split('~');
            startDate = strs[0];
            endDate = strs[1];
        }
        // 返回的数据
        var data = {
            currentPage: page ? page : 1,
            pageRowNum: 10,
            newsType: "newsType1",
            //mtype: "News_Platform_GetNewsListByTitles",
            pageNum: page || 1, // 请求页码: 1,2,3…
            perPageNum: 10, // 每页条数: 1,2,3…
        };
        if (state == 'search')
        {
            $.extend(data, {
                title: $('#txt_title').val(),
                author: $('#txt_author').val(),
                startDate: startDate,
                endDate: endDate
            });
        }
        $.ajax({
            type: "post",
            async: false,
            //url: "/BaseAshx/NewsManage/News_Platform.ashx",
            url: baseUrl + "news/getNewsList",
            data: data,
            datatype: "json",
            success: function (result) {
                result = JSON.parse(result);
                if (result.code == 200) {
                    if (!result.data.table || result.data.total == 0) {
                        $('#userTable').html('<div style="height: 100px;line-height:100px;text-align: center;font-size: xx-large;color: #666;">无数据</div>');
                        $('#pagination').html('');
                        return;
                    }
                    var html = "<tbody>" +
                    "<tr class='head' align='center'>" +
                            "<th>标题</th>" +
                            "<th>作者</th>" +
                            //"<th>内容</th>" +
                            "<th>来源</th>" +
                            "<th>机构</th>" +
                            "<th>是否为幻灯</th>" +
                            "<th>创建人</th>" +
                            "<th>创建时间</th>" +
                        "</tr>";
                    result.data.table.map(function (item, index) {
                        var isSlide = item.ISSLIDE;
                        var slide;
                        if (isSlide == "1") {
                            slide = "是";
                        } else {
                            slide = "否";
                        }
                        html += '<tr titleid="' + item.TITLEID + '" align = "center">'+
                           ' <td>' + item.TITLE + '</td>'+
                           '<td>' + item.AUTHOR + '</td>'+
                           //'<td>' + item.CLOB + '</td>'+
                          ' <td>' + item.SOURCE + '</td>'+
 '<td departmentId="' + item.DEPARTMENTID + '">' + item.DEPARTMENT + '</td>'+
           '<td picPath="' + item.PICPATH + '">' + slide + '</td>'+
           '<td >' + item.REPORTER + '</td>'+
           '<td>' + item.CREATETIME + '</td><td style="display:none">' + item.CLOB + '</td></tr>';

                    });
                    html += '</tbody>';
                    $('#userTable').html(html);
                    // $('#tableTitleDiv table').append(html);
                    var data = {
                        pageTotal: Math.ceil(result.data.total / 10),
                        pageAmount: 10, // 每页多少条
                        dataTotal: result.data.total,
                        curPage: 1
                    };
                    if (isSecond) {
                        return;
                    };
                    new Page({
                        id: 'pagination',
                        pageTotal: data.pageTotal, //必填,总页数（最少1页）
                        pageAmount: data.pageAmount, //每页多少条
                        dataTotal: data.dataTotal, //总共多少条数据（至少1条）
                        curPage: data.curPage, //初始页码,不填默认为1
                        pageSize: data.pageSize, //分页个数,不填默认为5
                        showPageTotalFlag: true, //是否显示数据统计,不填默认不显示
                        showSkipInputFlag: true, //是否支持跳转,不填默认不显示
                        getPage: function (page) {
                            // 请求数据
                            if (state == 'search') {
                                getTitleList('search', page, true);
                            } else {
                                getTitleList('',page, true);
                            }
                            
                        }
                    });
                } else {
                    layer.msg(result.msg, {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
            },
            error: function (error) {
                console.log(error);
            }
        });

    }
    //初始化
    getTitleList('');
    //搜索
    $('#btn_search').on('click', function () {
        getTitleList('search');
    });
    //时间控件
    layui.use('laydate', function () {
        var laydate = layui.laydate;

        //laydate.render({
        //    elem: '#txt_strdate' //指定元素
        //});
        laydate.render({
            elem: '#txt_date'
            , range: '~'
        });
    });
    
    // 选中用户
    $('#userTable').on('click', 'tr', function (e) {
        var $currentTarget = $(e.currentTarget);
        if (!$currentTarget.hasClass('head')) {
            if ($currentTarget.hasClass('curSelectedNode')) {
                $currentTarget.removeClass('curSelectedNode');
            } else {
                $('#userTable .curSelectedNode').removeClass('curSelectedNode');
                $currentTarget.addClass('curSelectedNode');
            }
        } else { }
        if ($('#userTable .curSelectedNode').length) {
            $('.editBtn, .deleteBtn, .resetPassWordBtn').removeClass('unable');
        } else {
            $('.editBtn, .deleteBtn, .resetPassWordBtn').addClass('unable');

        }
    });


    // 删除
    $('.deleteBtn').on('click', function () {
        var id = $('.curSelectedNode').attr('titleid');
        var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        //console.log(nowNode);
        var $td = $('#userTable .curSelectedNode td');
        var content = '<div>\n' +
            '<a id="check">确定删除当前所选平台新闻吗?</a>\n' +
            '</div>';

        layer.open({
            //id: 3,
            type: 1,
            title: '删除平台新闻',
            skin: 'layui-layer-prompt',
            content: content,
            btn: ['确定', '取消'],
            area: ['300px', '165px'],
            shadeClose: true, //点击遮罩关闭
            btn2: function (index, layero) {
                layer.close(index);
            },
            btn1: function (index, layero) {
                $.ajax({
                    type: 'post',
                    async: false,
                    url: baseUrl + "news/deleteNews",
                    //url: '/BaseAshx/NewsManage/News_Platform.ashx',
                    data: {
                        //mtype: "News_Platform_Delete",
                        newsType: "newsType1",
                        id: id
                    },
                    datatype: 'json',
                    success: function (result) {
                        result = JSON.parse(result);
                        if (result.code == 200) {
                            layer.msg('删除成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            getTitleList('');
                            layer.close(index);
                        } else {
                            layer.msg('删除失败', {
                                shade: 0.3,
                                time: 1000
                            });
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });

            },
        });


    });




    var nowNode;
    var textareaid = "";
    //添加
    $('.addBtn').on('click', function () {
        var html = "";
        
        html += '<span>' + '标题' + '：</span><input id="txt_title" type="text" class="layui-layer-input" autocomplete="off" value="" maxlength="50"><br/ >';
        html += '<span>' + '作者' + '：</span><input id="txt_author" type="text" class="layui-layer-input" autocomplete="off" value="" maxlength="25"><span id="source">' + '来源' + '：</span><input id="txt_source" type="text" class="layui-layer-input" autocomplete="off" value=""><br/ >';
        html += '<span>' + '机构' + '：</span><input id="orgInput" type="text" class="layui-layer-input" autocomplete="new-password" readonly="readonly"   value=""><br/ >';
        html += '<span>' + '是否为幻灯' + '：</span> <input type="radio" name="isSlide"  value="1" title="是">&nbsp;&nbsp;&nbsp;<font style="cursor:pointer;">是</font>&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio"  name="isSlide" value="0" title="否" checked>&nbsp;&nbsp;&nbsp;<font style="cursor:pointer;">否</font><span id="span">' + '图片' + '：</span> <input id="txt_picPath" type="text" class="layui-layer-input" value=""><a id="yulan_a" href="javascript:void(0);"  >预览</a><input id="fliePhoto" style="display:none;" type="file"/><br/ >';
        html += '<div style="position:relative"><span>' + '内容' + '：</span><textarea id="demo" style="display: none;"></textarea><br/ ></div>';

        var content = '<div>' + html + '</div>';

        //< a href="javascript:void(0);" style="font-size:10px;" onclick=" + viewPhoto()+ ">预览</a>
       
        var layedit,layedit1;
        layer.open({
            //id: 1,
            type: 1,
            title: '新建平台新闻',
            skin: 'layui-layer-prompt',
            content: content,
            btn: ['保存', '取消'],
            area: ['730px', '620px'],
            shadeClose: false, //点击遮罩关闭
            btn2: function (index, layero) {
                $('#ztreeDiv').hide();
                layer.close(index);
            },
            btn1: function (index, layero) {
                $('#ztreeDiv').hide();
                var title = layero.find('#txt_title').val();
                var author = layero.find('#txt_author').val();
                var clob = layedit.getContent(layedit1);
                var source = layero.find('#txt_source').val();
                var fk_dept = $('#orgInput').attr('checkid');
                var isSlide = $('input[name="isSlide"]:checked').val()
                var url = layero.find('#txt_picPath').val();
                var picPath = "/UpdateFile/" + url;
                layui.use('layedit', function () {
                    var layedit = layui.layedit;
                    layedit.build('myEdit'); //建立编辑器
                });


                if (!title) {
                    layer.msg('请输入平台新闻标题', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!author) {
                    layer.msg('请输入作者', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!source) {
                    layer.msg('请输入来源', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!isSlide) {
                    layer.msg('请选择是否为幻灯', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                else {
                    if (parseInt(isSlide) == 1) {
                        if (!url) {
                            layer.msg('请选择图片', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                    }
                }
                if (!clob) {
                    layer.msg('请输入内容', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                $.ajax({
                    type: 'post',
                    async: false,
                    url: baseUrl + "news/addNewsList",
                    //url: '/BaseAshx/NewsManage/News_Platform.ashx',
                    data: {
                        //mtype: 'News_Platform_Add',
                        newsType: "newsType1",
                        title: title,
                        author: author,
                        clob: clob,
                        source: source,
                        reporter: getCookie("portalusername"),
                        fkDept: fk_dept,
                        isSlide:isSlide,
                        picPath: picPath
                    },
                    datatype: 'json',
                    success: function (result) {
                        result = JSON.parse(result);
                        if (result.code == 200) {
                            layer.msg('添加成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            getTitleList('');
                            layer.close(index);
                        } else {
                            layer.msg('添加失败', {
                                shade: 0.3,
                                time: 1000
                            });
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });

            },

        });
        var ifram
        layui.use('layedit', function () {
            layedit = layui.layedit;
            layedit1 = layedit.build('demo', {
                tool: [
                    'strong' //加粗
                     , 'italic' //斜体
                     , 'underline' //下划线
                     , 'del' //删除线
                     , '|' //分割线
                     , 'left' //左对齐
                     , 'center' //居中对齐
                     , 'right' //右对齐
                     , 'link' //超链接
                     , 'unlink' //清除链接
                     , 'face' //表情
                    // , 'image' //插入图片
                     , 'help' //帮助
                ],
                height: 287, //设置编辑器高度
                width: 530
            });
            var ifram = document.getElementById($('.layui-layedit-iframe iframe').attr('id'))
            var body = ifram.contentWindow.document.body;
            //body.style.color = "#FFFFFF";
            //$(body).html('hahhahahahahaha')
        });

        //图片浏览
        $('#yulan_a').on('click', function () {
            var photoPicpath = $("#txt_picPath")
            if (photoPicpath.val() == "" || photoPicpath.val() == null || photoPicpath.val() == "undefined") {
                var fileUpload = document.getElementById("fliePhoto");
                fileUpload.click();
            } else {
                var photoFileName= photoPicpath.val();
                open("/UpdateFile/" + photoFileName)
            }

        })
        $('#fliePhoto').change(function () {
            var file = this.files[0];
            var form = new FormData();
            form.append("stype", "uploadImg"); 
            form.append("file", file); 
            //form.append("userno", "admin");
            form.append("fileName", file.name);
            var xhr = new XMLHttpRequest();
            var action = "/BaseAshx/NewsManage/UpdateFile.ashx"; //上传服务的接口地址
            xhr.open("POST", action);
            xhr.send(form); //发送表单数据
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (xhr.responseText == "False") {
                        $("#txt_picPath").val("ainim.jpg");
                        isTransit = false;
                        alert("文件格式错误");
                    }
                    else {
                        $("#txt_picPath").val(xhr.responseText);
                        isTransit = true;
                    }
                    //var resultObj = JSON.parse(xhr.responseText);//处理返回的数据......
                }
            };
            document.getElementById('fliePhoto').value = null;
            //getNodeByID("fileUpload").value = null;
        })
         
        

        // 点击选择部门
        $('#orgInput').on('click', function () {
            if ($('#ztreeDiv').is(':hidden')) {
                var top = $('#orgInput').offset().top + $('#orgInput').height() + 3;
                var left = $('#orgInput').offset().left;
                $('#ztreeDiv').show().css({
                    top: top,
                    left: left
                });
            } else {
                $('#ztreeDiv').hide();
            }
        });
        jQuery.fn.isChildOf = function (b) {
            return (this.parents(b).length > 0);
        };
        $('#orgInput')[0].addEventListener('blur', function (e) {
            //若是由点击引起的焦点改变，捕获点击了的元素
            var ele = e.relatedTarget;
            console.log(ele);
            if (!$(ele).isChildOf('#ztreeDiv')) {
                $('#ztreeDiv').hide();
            }
        }, false);

        //点击单选框后面的文字时点击单选框
        $("input[type=radio]+font").click(function (evt) {
            $(evt.currentTarget).prev().click();
            //var fontNode = $(evt.currentTarget).prev().click();
        });

    });


    
 

    //修改
    $('.editBtn').on('click', function () {
        var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        var $td = $('#userTable .curSelectedNode td');
        var titleId = $('#userTable .curSelectedNode').attr('titleid');

        var html = "";
        html += '<span>' + '标题' + '：</span><input id="txt_title" type="text" class="layui-layer-input" autocomplete="off" value="'+$td.eq(0).html()+'"><br/ >';
        html += '<span>' + '作者' + '：</span><input id="txt_author" type="text" class="layui-layer-input" autocomplete="off" value="' + $td.eq(1).html() + '"><span id="source">' + '来源' + '：</span><input id="txt_source" type="text" class="layui-layer-input" autocomplete="off" value="' + $td.eq(2).html() + '"><br/ >';
        html += '<span>' + '机构' + '：</span><input id="orgInput" type="text" class="layui-layer-input" autocomplete="new-password" readonly="readonly" checkid="' + $td.eq(3).attr('departmentId') + '" value="' + $td.eq(3).html() + '"><br/ >';
        html += '<span>' + '是否为幻灯' + '：</span> <input id="radio1" type="radio" name="isSlide" value="1" title="是">&nbsp;&nbsp;&nbsp;<font style="cursor:pointer;">是</font>&nbsp;&nbsp;&nbsp;&nbsp;<input  id="radio0" type="radio" name="isSlide" value="0" title="否" >&nbsp;&nbsp;&nbsp;<font style="cursor:pointer;">否</font><span id="span">' + '图片' + '：</span> <input id="txt_picPath" type="text" class="layui-layer-input" value="' + $td.eq(4).attr('picPath') + '"><a id="yulan_a" href="javascript:void(0);"  >预览</a><input id="fliePhoto" style="display:none;" type="file"/><br/ >';
        html += '<div style="position:relative"><span>' + '内容' + '：</span><textarea id="demo" style="display: none;"></textarea><br/ ></div>';
        
        var content = '<div>' + html + '</div>';
       
        var layedit, layedit1;

        var clob = $td.eq(7).html();
        layer.open({
            //id: 1,
            type: 1,
            title: '修改新闻',
            skin: 'layui-layer-prompt',
            content: content,
            btn: ['保存', '取消'],
            area: ['730px', '620px'],
            shadeClose: false, //点击遮罩关闭
            btn2: function (index, layero) {
                $('#ztreeDiv').hide();
                layer.close(index);
            },
            btn1: function (index, layero) {
                $('#ztreeDiv').hide();
                var title = layero.find('#txt_title').val();
                var author = layero.find('#txt_author').val();
                var clob = layedit.getContent(layedit1);
                var source = layero.find('#txt_source').val();
                var fk_dept = $('#orgInput').attr('checkid');
                var isSlide = $('input[name="isSlide"]:checked').val()
                var url = layero.find('#txt_picPath').val();
                var picPath = "";
                if (url.indexOf("/") != -1) {
                    picPath = url;
                } else {
                    picPath = "/UpdateFile/" + url;
                }
                layui.use('layedit', function () {
                    var layedit = layui.layedit;
                    layedit.build('myEdit'); //建立编辑器
                });

                if (!title) {
                    layer.msg('请输入新闻标题', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!author) {
                    layer.msg('请输入作者', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!source) {
                    layer.msg('请输入来源', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!isSlide) {
                    layer.msg('请选择是否为幻灯', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                else {
                    if (parseInt(isSlide) == 1) {
                        if (!url) {
                            layer.msg('请选择图片', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        }
                    }
                }
                if (!clob) {
                    layer.msg('请输入内容', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                $.ajax({
                    type: 'post',
                    async: false,
                    url: baseUrl + "news/updateNews",
                    //url: '/BaseAshx/NewsManage/News_Platform.ashx',
                    data: {
                        //mtype: 'News_Platform_Update',
                        newsType: "newsType1",
                        id: titleId,
                        title: title,
                        author: author,
                        clob: clob,
                        source: source,
                        department: fk_dept,
                        isSlide: isSlide,
                        picPath: picPath
                    },
                    datatype: 'json',
                    success: function (result) {
                        result = JSON.parse(result);
                        if (result.code == 200) {
                            layer.msg('修改成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            getTitleList('');
                            layer.close(index);
                        } else {
                            layer.msg('修改失败', {
                                shade: 0.3,
                                time: 1000
                            });
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });

            },
        });
        layui.use('layedit', function () {
            layedit = layui.layedit;
            layedit1 = layedit.build('demo', {
                tool: [
                    'strong' //加粗
                     , 'italic' //斜体
                     , 'underline' //下划线
                     , 'del' //删除线
                     , '|' //分割线
                     , 'left' //左对齐
                     , 'center' //居中对齐
                     , 'right' //右对齐
                     , 'link' //超链接
                     , 'unlink' //清除链接
                     , 'face' //表情
                    // , 'image' //插入图片
                     , 'help' //帮助
                ],
                height: 287, //设置编辑器高度
                width: 530
            });
            var ifram = document.getElementById($('.layui-layedit-iframe iframe').attr('id'))
            var body = ifram.contentWindow.document.body;
            //body.style.color = "#FFFFFF";
            $(body).html(clob)
        });
        var isSlide = $td.eq(4).html();
        var radio = document.getElementById("radio0");
        if (isSlide == '是')

            $("#radio1").attr("checked", "checked");
        else
            $("#radio0").attr("checked", "checked");
       
        //图片预览
        $('#yulan_a').on('click', function () {
            var photoPicpath = $("#txt_picPath")
            if (photoPicpath.val() == "" || photoPicpath.val() == null || photoPicpath.val() == "undefined") {
                var fileUpload = document.getElementById("fliePhoto");
                fileUpload.click();
            } else {
                var photoFileName = photoPicpath.val();
                open("/UpdateFile/" + photoFileName)
            }

        })
        $('#fliePhoto').change(function () {
            var file = this.files[0];
            var form = new FormData();
            form.append("stype", "uploadImg");
            form.append("file", file);
            //form.append("userno", "admin");
            form.append("fileName", file.name);
            var xhr = new XMLHttpRequest();
            //var action = "/BaseAshx/NewsManage/UpdateFile.ashx"; //上传服务的接口地址
            var action = "http://localhost:8886/sw/upload/uploadImg";
            xhr.open("POST", action);
            xhr.send(form); //发送表单数据
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (xhr.responseText == "False") {
                        $("#txt_picPath").val("ainim.jpg");
                        isTransit = false;
                        alert("文件格式错误");
                    }
                    else {
                        $("#txt_picPath").val("/" + JSON.parse(xhr.responseText).data);
                        isTransit = true;
                    }
                    //var resultObj = JSON.parse(xhr.responseText);//处理返回的数据......
                }
            };
            document.getElementById('fliePhoto').value = null;
            //getNodeByID("fileUpload").value = null;
        })
        // 点击选择部门
        $('#orgInput').on('click', function () {
            if ($('#ztreeDiv').is(':hidden')) {
                var top = $('#orgInput').offset().top + $('#orgInput').height() + 3;
                var left = $('#orgInput').offset().left;
                $('#ztreeDiv').show().css({
                    top: top,
                    left: left
                });
            } else {
                $('#ztreeDiv').hide();
            }
        });
        jQuery.fn.isChildOf = function (b) {
            return (this.parents(b).length > 0);
        };
        $('#orgInput')[0].addEventListener('blur', function (e) {
            //若是由点击引起的焦点改变，捕获点击了的元素
            var ele = e.relatedTarget;
            console.log(ele);
            if (!$(ele).isChildOf('#ztreeDiv')) {
                $('#ztreeDiv').hide();
            }
        }, false);

        //点击单选框后面的文字时点击单选框
        $("input[type=radio]+font").click(function (evt) {
            $(evt.currentTarget).prev().click();
            //var fontNode = $(evt.currentTarget).prev().click();
        });

    })


   
  





    // 根节点id(自定义)
    var rootNodeId = '101010';

    var settingLeft = {
        view: {
            dblClickExpand: false, //双击节点时，是否自动展开父节点的标识
            showLine: false, //是否显示节点之间的连线
            showIcon: true,
            fontCss: {
                //'color': 'white',
                'font-weight': 'normal'
            }, //字体样式函数
            selectedMulti: false //设置是否允许同时选中多个节点
        },
        check: {
            //chkboxType: { "Y": "ps", "N": "ps" },
            chkStyle: "checkbox", //复选框类型
            enable: false //每个节点上是否显示 CheckBox
        },
        data: {
            simpleData: { //简单数据模式
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {          
            onClick: function (event, treeId, treeNode) {
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left");
                if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                    zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                }
                var text = $(event.target).text();
                var id = treeNode.id;
                console.log(id);
                console.log(text);
                
                if (text) {
                    $('#orgInput').val(text);
                    $('#orgInput').attr('checkid', id);
                    $('#ztreeDiv').hide();
                }
            },
            onDblClick: function (treeId, treeNode) {
                //code
            }
        }
    };
    // 获取机构组织数据
    var zNodes;
    $.ajax({
        type: "post",
        async: false,
        url: baseUrl + "dept/getAllDepts",
        //url: "/BaseAshx/Org/OrgAshx.ashx",
        data: {
            stype: 'OrgManage_QueryOrgTree',
            orgid: getCookie("portaluserdept"),
            treetype: 'down'
        },
        datatype: "json",
        success: function (result) {
            result = JSON.parse(result);
            if (result.code == 200) {
                var data = result.data;
                zNodes = data.map(function (item, index) {
                    // console.log(item);
                    var mapResult = {
                        "id": item.ORG_ID,
                        "name": item.ORGSHORTNAME,
                        "pId": item.ORG_PID,
                    };
                    if (index == 0) {
                        mapResult.open = true;
                    }
                    return mapResult;
                });
                //初始化菜单树
                $.fn.zTree.init($("#menu_tree_left"), settingLeft, zNodes);
            } else {
                layer.msg('获取机构数据错误,请稍候再试', {
                    shade: 0.3,
                    time: 1000 // 1秒关闭
                });
            }
        },
        error: function (error) {
            console.log(error);
        }
    });


})


